<template>
  <div class="login-container">       
    <!-- 左侧背景图与标题 -->
    <div class="left-panel">
      <div class="description">
        <h2>停车缴费管理系统</h2>
        <p>欢迎使用本系统</p>
      </div>
    </div>
    <!-- 右侧登录表单 -->
    <div class="right-panel">
      <div class="login-form">
        <h2>登录</h2>
        <el-form :model="form" :rules="rules" ref="loginForm" label-position="top" label-width="0px">
          <el-form-item size="large" label="用户名" prop="userName">
            <el-input v-model="form.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item size="large" label="密码" prop="password">
            <el-input type="password" v-model="form.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item size="large">
            <el-button type="primary" @click="onLogin" :loading="loading" style="width:100%; font-size: 16px;">登录</el-button>
          </el-form-item>
          <a href="javascript:void(0)" @click="showRegisterDialog = true">没有账号？点我注册</a>
        </el-form>
      </div>
    </div>
    <!-- 注册对话框 -->
    <el-dialog v-model="showRegisterDialog" class="register-form" width="30%" center>
        <h2>注册</h2>
        <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-position="top" label-width="0px">
          <el-form-item label="用户名" prop="newUserName">
            <el-input v-model="registerForm.newUserName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="newPassword">
            <el-input type="password" v-model="registerForm.newPassword" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="registerForm.confirmPassword" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮件" prop="email">
            <el-input v-model="registerForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="registerForm.phone" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button type="primary" @click="onRegister">确定</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </span>
    </el-dialog>
    <div class="copyright">
      Copyright ©2025 SHOU-QYT-SmartPark
    </div>
  </div>
</template>

<script>
import JSEncrypt from 'jsencrypt';
import axios from 'axios';
import { mapActions } from 'vuex';

const api = axios.create({
    baseURL:'http://localhost:8092'
})
export default {
  data() {
    return {
      form: {
        userName: '',
        password: ''
      },
      rules: {
        userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      loading: false,
      showRegisterDialog: false,
      registerForm: {
        newUserName: '',
        newPassword: '',
        confirmPassword: '',
        email: '',
        phone: ''
      },
      registerRules: {
        newUserName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        newPassword: [{ required: true, message: '请输入密码', trigger: 'blur' },{ min: 6, message: '密码长度至少为6位', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' },
          { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [{ required: false}]
      }
    };
  },
  methods: {
    ...mapActions(['fetchPublicKey']), // 映射 Vuex 的 fetchPublicKey 方法
    async fetchRSAKey() {
      try {
        await this.fetchPublicKey();
      } catch (error) {
        console.error('获取公钥失败:', error);
        this.$notify.error({
          title: '错误',
          message: '获取公钥失败，请稍后再试。',
        });
      }
    },
    // 加密函数
    encryptPassword(password) {
      const encryptor = new JSEncrypt();
      encryptor.setPublicKey(this.$store.getters.publicKey); // 设置公钥
      return encryptor.encrypt(password); // 返回加密后的密码
    },
    onLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 加密密码
          const encryptedPassword = this.encryptPassword(this.form.password);
          console.error("传入后端的密码"+encryptedPassword);
          api.post('/api/v1/user/login', {
            userName: this.form.userName,
            password: encryptedPassword
          }).then(response => {
            this.loading = false;
            if (response.data.code == "200") {
              const { id, name, email, phone, createTime, UpdateTime, role, token } = response.data.data;
              localStorage.setItem("token", token); // 将token保存到localStorage中
              console.log(JSON.stringify(response.data.data));
              localStorage.setItem("id", id); 
              localStorage.setItem("name", name); 
              localStorage.setItem("email", email); 
              localStorage.setItem("phone", phone); 
              localStorage.setItem("createTime", createTime); 
              localStorage.setItem("UpdateTime", UpdateTime); 
              localStorage.setItem("role", role); 
              // const routeName = role === "普通用户" ? 'UserAccount' : 'AdminDashboard';
              this.$router.push({
                name: 'AdminDashboard',
              });
              this.$notify({
                title: '成功',
                message: '登录成功',
                type: 'success'
              });
            } else {
              this.$notify.error({
                title: '错误',
                message: response.data.message || '未知错误'
              });
            }
          }).catch(error => {
            this.loading = false;
            console.error('登录请求失败:', error);
            this.handleError(error);
          });
        } else {
          console.log('验证失败!');
          return false;
        }
      });
    },
    handleError(error) {
      if (error.response && error.response.data && error.response.data.message) {
        this.$notify.error({
          title: '错误',
          message: error.response.data.message
        });
      } else {
        this.$notify.error({
          title: '错误',
          message: '请求过程中发生错误，请稍后再试。'
        });
      }
    },  
    onRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          // 加密密码
          const encryptedPassword = this.encryptPassword(this.registerForm.newPassword);
          api.post('/api/v1/user/register', {
            name: this.registerForm.newUserName,
            password: encryptedPassword,
            email: this.registerForm.email,
            phone: this.registerForm.phone,
            role: "普通用户"
          }).then(response => {
            if (response.data.code == "200") {
              this.showRegisterDialog = false;
              this.resetRegisterForm();
              this.$alert('注册成功', '成功', {
                confirmButtonText: '确定',
                type: 'success',
              });
            } else {
              this.$alert(response.data.message || '未知错误', '错误', {
                confirmButtonText: '确定',
                type: 'error'
              });
            }
          }).catch(error => {
            console.error('注册请求失败:', error);
            if (error.response && error.response.data && error.response.data.message) {
              this.$notify.error({
                title: '错误',
                message: error.response.data.message
              });
            } else {
              this.$notify.error({
                title: '错误',
                message: '请求过程中发生错误，请稍后再试。'
              });
            }
          });
        } else {
          console.log('验证失败!');
          return false;
        }
      });
  },
    resetRegisterForm() {
      this.registerForm = {
        newUserName: '',
        newPassword: '',
        confirmPassword: '',
        email: '',
        phone: ''
      }
    },
    handleCancel() {
      this.showRegisterDialog = false;
      this.resetRegisterForm();
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.registerForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    }
  },
  mounted() {
    // 页面加载时获取公钥
    this.fetchPublicKey();
  }
}

</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  justify-content: space-between; /* 调整为space-between以充分利用空间 */
  position: relative; /* 确保子元素可以相对于此容器定位 */
  background: url('image/car.jpg') no-repeat center center fixed; 
  background-size: cover; 
}

.left-panel {
  width: 58%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  text-align: center;
  background-color: transparent;
}
.left-panel .description h2 {
  font-size: 36px; 
  color: black; 
  margin-bottom: 50px; 
}

.left-panel .description p {
  font-size: 20px; 
  color: #242526; 
}

.right-panel {
  background-color: #f8f9fa;
  width: 42%;
  display: flex;
  justify-content: center;
  align-items: flex-start; 
  margin-top: 30px; 
  background-color: transparent;
}

.login-form {
  width: 80%;
  height: 500px;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.9); /* 白色背景，透明度为0.7 */
  border-radius: 8px;
}

::v-deep .register-form {
  width: 30%;
  height: 700px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 1); 
  border-radius: 8px;
}

h2 {
  margin-bottom: 20px;
  text-align: center;
}

/* 调整Element UI的默认样式以确保标签和输入框垂直排列 */
/* ::v-deep是vue3提供的深度选择器，.el-form-item__label是element-plus官方定义的类 */
::v-deep .el-form-item__label {
  line-height: normal;
  font-size: 18px;
  color: #606266;
}
::v-deep .el-input__inner {
  height: 45px; 
  line-height: 45px; 
}
/* 添加版权信息样式 */
.copyright {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f8f9fa;
  padding: 10px 0;
  text-align: center;
  font-size: 16px;
  color: #606266;
  background-color: transparent;
  font-weight: bold;
}
/* 注册表单的确认和取消按钮 */
.dialog-footer {
  display: flex;
  justify-content: space-evenly; 
  margin-top: 20px; 
}

.dialog-footer .el-button {
  width: 40%;
  height: 50px; /* 调整按钮高度 */
  font-size: 16px;
}
</style>